import { IManagement } from "@/api";
import { Modal, ModalProps } from "@/components";
import { RenderFormItems } from "@/components/SearchForm/partials/RenderFormItem";
import { Operate } from "@/enums";
import { getModalFields } from "./helper";
import { Form, message } from "antd";
import { createManagement, updateManagement } from "../../service";

interface TaskModal extends ModalProps {
  data?: IManagement.ResManagementItem;
}

export const TaskModal = ({
  data,
  onCancel: _onCancel,
  refresh,
  ...restProps
}: TaskModal) => {
  const modelType = data ? Operate.Status.UPDATE : Operate.Status.CREATE;
  const modelTitle = Operate.Title[modelType];
  const [form] = Form.useForm();

  form.setFieldsValue(data);

  const onOk = async () => {
    const value = await form.validateFields();
    const { id } = form.getFieldsValue(true);

    const [err, data] = await (id ? updateManagement : createManagement)({
      id,
      ...value,
    });

    if (err) return message.error(err);
    message.success(`${id ? "编辑" : "创建"}成功`);
    onCancel();
    refresh();
  };

  const onCancel = () => {
    _onCancel?.();
    form.resetFields();
  };
  return (
    <Modal
      width={800}
      title={`${modelTitle}任务`}
      onOk={onOk}
      onCancel={onCancel}
      {...restProps}
    >
      <Form form={form} labelCol={{ span: 6 }}>
        <RenderFormItems formConfigs={getModalFields(data)} />
      </Form>
    </Modal>
  );
};
